import {
    PlatformRuntime,
    StorageInterface,
    toolExists,
    getTool,
    FeatureInterface,
    tools,
    Initializer,
} from "ctool-config";
import storagefocusany from "./storage";

type FeatureItem = { feature: FeatureInterface, cmds: string[] }

const $t = (key: string): string => {
    // @ts-ignore
    return window["$t"](key);
};

const setActions = (items: any) => {
    try {
        window.focusany.setAction(items);
    } catch (e) {

    }
};

export const runtime = new (class implements PlatformRuntime {
    name = "focusany";

    is() {
        return navigator.userAgent.includes("focusany");
    }

    openUrl(url: string) {
        return window.focusany.shellOpenExternal(url);
    }

    storage(): StorageInterface {
        return storagefocusany;
    }

    getLocale() {
        return "zh_CN";
    }

    initialize(initializer: Initializer) {

        try {
            // focusany 动态关键字初始化设置
            if (window.focusany.getActions().length === 0) {
                this.resetActions();
            }
        } catch (e) {
        }

        focusany.onPluginReady(({actionName, actionMatch, requestId}) => {

            // console.log('onPluginReady', actionName, actionMatch);

            focusany.showMainWindow();
            if (!actionName.includes("ctool-")) {
                return;
            }
            const [, _tool, _feature] = actionName.split("-");
            if (!toolExists(_tool)) {
                return;
            }

            const tool = getTool(_tool);
            if (!tool.existFeature(_feature)) {
                return;
            }
            const feature = tool.getFeature(_feature);

            const query: Record<string, string> = {};
            if (actionMatch) {
                const query1 = focusany.getQuery(requestId);
                // 输入框数据写入临时存储
                if (["key", "regex"].includes(actionMatch.type)) {
                    initializer.storage().setNoVersion("_temp_input_storage", query1.keywords, 10);
                    //添加随机数 防止页面不刷新
                    query["_t"] = `${Math.random()}`;
                }
                // 设置功能搜索关键字
                if (actionMatch.type === "text") {
                    query.keywords = query1.keywords;
                }
            }
            initializer.push(feature.getRouter(), query);
        });
    }

    getFeatures() {
        const result = new Map<FeatureInterface, string[]>();
        tools.forEach(tool => {
            tool.features.forEach(feature => result.set(feature, []));
        });
        window.focusany.getActions()
            .filter(item => item.name.includes("ctool-") && item.name.includes("-customize"))
            .forEach(item => {
                const [, _tool, _feature] = item.name.split("-");
                if (!toolExists(_tool)) {
                    return null;
                }
                const tool = getTool(_tool);
                if (!tool.existFeature(_feature)) {
                    return null;
                }
                const feature = tool.getFeature(_feature);
                const names = item.matches.map(m => (m as ActionMatchText).text);
                result.set(feature, names);
            });

        return result;
    }

    resetActions() {
        let features: FeatureItem[] = [];
        tools.forEach(tool => {
            tool.features.forEach(feature => {
                features.push({
                    feature: feature,
                    cmds: [
                        ...(
                            new Set([
                                    tool.name,
                                    feature.name,
                                    // tool.isSimple() ? `ctool-${tool.name}` : `ctool-${tool.name}-${feature.name}`,
                                    $t(`tool_${tool.name}`),
                                    $t(`tool_${tool.name}_${feature.name}`),
                                    ...$t(`tool_${tool.name}_${feature.name}_keywords`).split(","),
                                    `${tool.isSimple() ? "" : $t(`tool_${tool.name}`) + ""}${$t(`tool_${tool.name}_${feature.name}`)}`,
                                ].map(item => item.trim().toLowerCase()).filter(item => item !== ""),
                            )
                        ),
                    ],
                });
            });
        });
        this.setActions(features);
    }

    setActions(features: FeatureItem[]) {

        // 移除已有项目
        window.focusany.getActions().forEach(item => {
            if (item.name.includes("ctool-") && item.name.includes("-customize")) {
                // @ts-ignore
                window.focusany.removeAction(item.name);
            }
        });

        const keySet = new Set<string>()

        // 添加项目
        features.forEach(({feature, cmds}) => {
            if (cmds.length > 0) {
                const matches = cmds
                    .filter(cmd => {
                        // 避免太多重复的内容
                        if (keySet.has(cmd)) {
                            return false
                        }
                        keySet.add(cmd)
                        return true
                    })
                    .map(cmd => {
                        // console.log('cmd', JSON.stringify([feature.tool.name, feature.tool.name, cmd]))
                        return {
                            type: 'text',
                            text: cmd,
                        }
                    })
                if (!matches.length) {
                    return
                }
                // console.log('feature', `ctool-${feature.getKey()}-customize`, feature.tool.isSimple(), feature.tool.name, JSON.stringify(matches.map(o => o.text)))
                setActions({
                    "name": `ctool-${feature.getKey()}-customize`,
                    "title": `${feature.tool.isSimple() ? "" : $t(`tool_${feature.tool.name}`) + "-"}${$t(`tool_${feature.tool.name}_${feature.name}`)}`,
                    "matches": matches,
                });
            }
        });
    }
});
